package org.qiancizhan.UI;

import org.qiancizhan.Controller.CollectionController;
import org.qiancizhan.Controller.WordController;
import org.qiancizhan.Model.DTO.BookWordsDTO;
import org.qiancizhan.Model.DTO.PageConfigDTO;
import org.qiancizhan.Model.POJO.VocabularyListPOJO;
import org.qiancizhan.Model.POJO.WordPOJO;
import org.qiancizhan.Model.VO.WordsVO;
import org.qiancizhan.Utils.UIFormatUtli;

import java.util.Scanner;
import java.util.function.Consumer;
import java.util.function.Function;

public class BookWordsUI {
    private final Scanner sc = new Scanner(System.in);
    private final WordController wordController = new WordController();
    private final CollectionController collectionController = new CollectionController();

    public void showBookIndex(VocabularyListPOJO bookData) {
        UIFormatUtli.log(String.format("书名：%s\t单词数量：%d", bookData.getBook_name(), bookData.getWord_count()));

        PageConfigDTO pageConfig = getPageConfig(bookData.getWord_count());
        if (pageConfig == null) return;

        Function<PageConfigDTO, WordsVO> wordsProvider = config ->
                wordController.getWords(new BookWordsDTO(bookData.getTable_name(), bookData.getWord_count(), config));

        showWordsNavigation(wordsProvider, pageConfig, "收藏", this::addCollection);
    }

    public void showCollectionWords() {
        int totalWords = collectionController.getUserWord_count();
        if (totalWords == 0) {
            System.out.println("您没有收藏的单词,去收藏单词吧");
            return;
        }

        UIFormatUtli.log(String.format("我收藏的单词数量：%d", totalWords));
        PageConfigDTO pageConfig = getPageConfig(totalWords);
        if (pageConfig == null) return;

        showWordsNavigation(collectionController::getUserCollectionWords, pageConfig, "取消收藏", this::removeCollection);
    }

    private PageConfigDTO getPageConfig(int totalWords) {
        System.out.println("请填写书本配置:");
        System.out.println("例子:1 10,表示页面1，每页展示10个");

        while (true) {
            String[] parts = sc.nextLine().trim().split(" ");

            if (parts.length != 2) {
                System.out.println("输入格式错误，请重新输入");
                continue;
            }

            try {
                int pageNum = Integer.parseInt(parts[0]);
                int pageSize = Integer.parseInt(parts[1]);
                int totalPages = (int) Math.ceil((double) totalWords / pageSize);

                if (pageSize < 5 || pageSize > 20) {
                    System.out.println("每页展示数量必须在5-20之间，请重新输入");
                    continue;
                }

                if (pageNum < 1 || pageNum > totalPages) {
                    System.out.println("页面范围必须在1-" + totalPages + "之间，请重新输入");
                    continue;
                }

                return new PageConfigDTO(pageNum, pageSize, totalPages);

            } catch (NumberFormatException e) {
                System.out.println("输入必须为数字，请重新输入");
            } catch (ArithmeticException e) {
                System.out.println("每页展示数量不能为0，请重新输入");
            }
        }
    }

    private void showWordsNavigation(Function<PageConfigDTO, WordsVO> wordsProvider,
                                     PageConfigDTO config,
                                     String actionName,
                                     Consumer<WordActionContext> actionHandler) {
        WordsVO wordsData = wordsProvider.apply(config);

        while (true) {
            displayWords(wordsData);

            String menu = String.format("当前页：%d/%d页\t1.上一页\t2.下一页\t[3.n] %s第n个单词%s\t0.退出",
                    wordsData.getPageConfig().getCurrentNum(),
                    wordsData.getPageConfig().getTotalNum(),
                    actionName,
                    actionName.equals("取消收藏") ? "\t9.清空收藏!" : "");

            UIFormatUtli.log(menu);

            String choice = sc.nextLine();

            if (handleNavigation(choice, wordsData, wordsProvider)) continue;
            if (handleWordAction(choice, wordsData, actionHandler)) continue;
            if (handleSpecialAction(choice, actionName)) break;
            if (choice.equals("0")) break;

            UIFormatUtli.log("输入错误，请重新输入");
        }
    }

    private void displayWords(WordsVO wordsData) {
        System.out.println(UIFormatUtli.HR);
        for (int i = 0; i < wordsData.getWords().size(); i++) {
            WordPOJO word = wordsData.getWords().get(i);
            System.out.printf("第%d个：%n%s%n%s%n%s%n", i + 1, word.getWord(), word.getTranslate(), UIFormatUtli.HR);
        }
    }

    private boolean handleNavigation(String choice, WordsVO wordsData, Function<PageConfigDTO, WordsVO> wordsProvider) {
        if (!choice.equals("1") && !choice.equals("2")) return false;

        PageConfigDTO config = wordsData.getPageConfig();
        int current = config.getCurrentNum();
        int total = config.getTotalNum();

        if (choice.equals("1")) {
            config.setCurrentNum(current <= 1 ? 1 : current - 1);
        } else {
            config.setCurrentNum(current >= total ? total : current + 1);
        }

        WordsVO newData = wordsProvider.apply(config);
        wordsData.getWords().clear();
        wordsData.getWords().addAll(newData.getWords());
        wordsData.setPageConfig(newData.getPageConfig());
        return true;
    }

    private boolean handleWordAction(String choice, WordsVO wordsData, Consumer<WordActionContext> actionHandler) {
        if (!choice.startsWith("3.")) return false;

        try {
            int index = Integer.parseInt(choice.substring(2)) - 1;
            if (index < 0 || index >= wordsData.getWords().size()) {
                System.out.println("输入错误，请重新输入");
                return true;
            }

            WordPOJO word = wordsData.getWords().get(index);
            actionHandler.accept(new WordActionContext(word, wordsData));
            sleep(500);

        } catch (NumberFormatException e) {
            System.out.println("输入格式错误，请使用 3.n 的格式");
        }
        return true;
    }

    private boolean handleSpecialAction(String choice, String actionName) {
        if (!choice.equals("9") || !actionName.equals("取消收藏")) return false;

        System.out.println("警告，确定清空收藏？1.确定,2.取消");
        if (sc.nextLine().equals("1") && collectionController.clearCollection()) {
            System.out.println("清空成功");
        } else {
            System.out.println("清空失败");
        }
        return true;
    }

    private void addCollection(WordActionContext context) {
        WordPOJO word = context.word;
        if (collectionController.addCollection(word)) {
            System.out.printf("收藏成功%s%n", word.getWord());
        } else {
            System.out.println("您已收藏该单词");
        }
    }

    private void removeCollection(WordActionContext context) {
        WordPOJO word = context.word;
        if (collectionController.delCollection(word.getId())) {
            System.out.printf("取消收藏成功%s%n", word.getWord());
        } else {
            System.out.println("该单词不存在你的收藏列表中");
        }
    }

    private void sleep(long millis) {
        try {
            Thread.sleep(millis);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }
    }

    private static class WordActionContext {
        final WordPOJO word;
        final WordsVO wordsData;

        WordActionContext(WordPOJO word, WordsVO wordsData) {
            this.word = word;
            this.wordsData = wordsData;
        }
    }
}